package org.sang.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * Created by sang on 2017/12/28.
 */
@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {
    /*
    * 参数authentication是从spring的全局缓存SecurityContextHolder中拿到的，里面是用户的权限信息
    * 参数object是url
    * 参数configAttributes所需的权限
    * 这里通过两层循环嵌套来确认当前用户所访问资源是否可以访问
    * 第一层 while (iterator.hasNext())：cas是由CustomMetadataSource（资源授权列表）获取的当前请求所要求的权限
    * 第二层 for (GrantedAuthority authority : authorities)：authorities是由Authentication（用户权限列表）获取的当前用户所拥有的权限
    * return：当确认通过或非法请求（例如用户输入不存在的地址）则返回，否则抛出异常
    * */
    @Override
    public void decide(Authentication auth, Object o, Collection<ConfigAttribute> cas){
        Iterator<ConfigAttribute> iterator = cas.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute ca = iterator.next();
            //当前请求需要的权限
            String needRole = ca.getAttribute();
            if ("ROLE_LOGIN".equals(needRole)) { //当没有匹配的权限时（即非法URL），先判断是否匿名访问，是则抛出异常
                if (auth instanceof AnonymousAuthenticationToken) {
                    throw new BadCredentialsException("未登录");
                } else
                    return; //这里控制可能有问题
            }
            //当前用户所具有的权限
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
            for (GrantedAuthority authority : authorities) {//这里采取的是开放原则 ，即只要用户有一个角色符合资源权限则放行
                if (authority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足!");
    }
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}